#include<iostream>
using namespace std;
class GraphNode {
public:
	string Data;
	GraphNode* next;
	GraphNode(string str = "V") {
		Data = str;
		next = NULL;
	}
};
class Graph {
public:
	GraphNode** tmp;
	char type;
	int n;
	Graph() {
		cin >> type >> n;
		tmp = new GraphNode * [n];
		for (int i = 0; i < n; i++) {
			string str;
			cin >> str;
			tmp[i] = new GraphNode(str);
		}
		int m;
		cin >> m;
		for (int i = 0; i < m; i++) {
			string str1, str2;
			cin >> str1 >> str2;
			GraphNode* p = new GraphNode(str2);
			for (int j = 0; j < n; j++) {
				if (tmp[j]->Data == str1) {
					GraphNode* cur = tmp[j];
					while (cur->next != NULL) {
						cur = cur->next;
					}
					cur->next = p;
				}
				if (type == 'U') {
					if (tmp[j]->Data == str2) {
						GraphNode* p1 = new GraphNode(str1);
						GraphNode* cur = tmp[j];
						while (cur->next != NULL) {
							cur = cur->next;
						}
						cur->next = p1;
					}
				}
			}
		}
	}
	void print_nn() {
		for (int i = 0; i < n; i++) {
			GraphNode* p = tmp[i];
			for (int j = 0; j < n; j++) {
				p = tmp[i]->next;
				int k = 0;
				while (p != NULL) {
					if (p->Data == tmp[j]->Data) {
						if (j == n - 1) {
							cout << '1';
						}
						else {
							cout << "1 ";
						}
						k = 1;
						break;
					}
					p = p->next;
				}
				if (k == 0) {
					if (j == n - 1) {
						cout << '0';
					}
					else {
						cout << "0 ";
					}
				}
			}
			cout << endl;
		}
	}
	void print_d() {
		if (type == 'U') {
			for (int i = 0; i < n; i++) {
				GraphNode* p = tmp[i];
				int m = 0;
				while (p->next != NULL) {
					p = p->next;
					m++;
				}
				cout << tmp[i]->Data;
				if (m != 0) {
					cout << ": " << m;
				}
				cout << endl;
			}
		}
		else {
			int* cur1 = new int[n];
			int* cur2 = new int[n];
			for (int i = 0; i < n; i++) {
				cur1[i] = 0;
				cur2[i] = 0;
			}
			for (int i = 0; i < n; i++) {
				GraphNode* p = tmp[i];
				while (p->next != NULL) {
					p = p->next;
					if (p != NULL) {
						for (int j = 0; j < n; j++) {
							if (p->Data == tmp[j]->Data) {
								cur2[j]++;
							}
						}
					}
					cur1[i]++;
				}

			}
			for (int i = 0; i < n; i++) {
				GraphNode* p = tmp[i];
				if (cur1[i] == 0 && cur2[i] == 0) {
					cout << tmp[i]->Data << endl;
				}
				else {
					cout << tmp[i]->Data << ':';

					cout << ' ' << cur1[i] << ' ' << cur2[i] << ' ' << cur1[i] + cur2[i] << endl;
				}
			}
		}
	}
};
int main()
{
	int t;
	cin >> t;
	for (int i = 0; i < t; i++) {
		Graph G;
		G.print_nn();
		G.print_d();
	}
	return 0;
}